import {
  encrypt
} from '@/utils/jsencrypt'
import {
  dateFormat
} from '@/utils/public.js'
import {
  wpgetData,
  wpsaveData,
  execApi,
  getWpIdByTable,
  userDefinedApi
} from '@/system/api/cellView'
import {
  getRepId
} from '@/system/api/cellEdit'



class userevent {
  constructor(thiz) {
    this.self = thiz
    this.autoRun()
    this.td = null
    this.trindex = -1
    this.tdindex = -1
    this.tr = null
    this.tableIndex = null
    this.rindex = null
    this.field = null
    this.doubleEvent = null
    this.events = []
    this.rowIndex = null
  }

  userEvent(func) {
    //运行脚本
    if (func) {
      let runfunc = new Function('self', 'thiz', func)
      return runfunc(this.self, this)
    }
    return null;
  }

  runEvent(type, ...params) {
    //运行表单定义事件
    this.td = null //初始  this.tr  this.td 信息
    this.trindex = -1
    this.tdindex = -1
    this.tr = null
    this.tableIndex = null
    this.rindex = null
    this.field = null
    this.microId = null
    params.forEach((item, i) => {
      //初始化参数
      switch (i) {
        case 0:
          this.trindex = item
          break
        case 1:
          this.tdindex = item
          break
        case 2:
          this.tr = item
          break
        case 3:
          this.td = item
          break
        case 4:
          this.microId = item
          break
      }
      if (this.td && this.td.com) {
        this.tableIndex = this.td.com.comattrs.tableIdx
        this.field = this.td.com.comattrs.fieldName
      }
      if (this.tr) {
        this.rindex = this.tr.rindex
      }
      if (this.microId) {
        this.microId = this.microId
      }
    })
    console.log(this.microId);
    //单元格点击 返回单元格信息
    if (type.indexOf('cellclick') > -1) {
      let val = null
      if (this.tableIndex && this.field) {
        val = this.self.info.table[this.tableIndex].record[this.rindex][this.field]
        this.self.$emit(type, this.tableIndex, this.rindex, this.field, val)
      }
    }
    if (!this.td || this.td.com == undefined || this.td.com == null) {
      return;
    }
    //字段变更的时候 向父窗口提交事件  并刷新下拉信息
    if (type.indexOf('change') > -1 || type.indexOf('clearable') > -1) {
      if ((this.self.info.table[this.td.com.comattrs.tableIdx].fields[this.tdindex].showType != 2) &&
        this.self.info.table[this.td.com.comattrs.tableIdx].fields.find(b => b.fieldName == this.td.com.comattrs.fieldName.toUpperCase()).showDetail) {
        // let sql = this.td.com.comattrs.showDetail
        // while (true){
        //     let l_idx = sql.indexOf("[");
        //     let r_idx = sql.indexOf("]");
        //     if (l_idx == -1 || r_idx == -1 || l_idx > r_idx){
        //         break;
        //     }
        //     let filedKey  =  sql.substring(l_idx+1, r_idx);
        //     let f_idx =  filedKey.indexOf(":");
        //     if (f_idx != 1){
        //         break;
        //     }
        //     let tableIdex = filedKey.substr(0,1);
        //     let recordIndex = 0;
        //     if (tableIdex == this.td.com.comattrs.tableIdx){
        //         recordIndex = this.tr.rindex;
        //     }

        //     filedKey = filedKey.substring(2);
        //     // console.log(this.tableset.trs,this.self.info.table[tableIdex].record[recordIndex],filedKey,this.self.info.table[tableIdex].record[recordIndex][filedKey])
        //     let fieldVal = this.self.info.table[tableIdex].record[recordIndex][filedKey];
        //     console.log(this.td.com.comattrs.showDetail,fieldVal,this.self.info.table[tableIdex].record[recordIndex],filedKey)
        //     sql = sql.substring(0, l_idx) + fieldVal + sql.substring(r_idx+1);
        //     console.log(sql)


        // }
        // //
        // if (this.td.com.comattrs.sql == sql) return;

        // this.td.com.comattrs.sql = sql 
        // this.self.$set(this.td.com.comattrs,'sql',sql)
        this.self.selectvisible(window.event, this.trindex, this.tdindex, this.tr, this.td)
        // console.log(this.self.info.table[this.td.com.comattrs.tableIdx].select[this.td.com.comattrs.fieldName.toUpperCase()].option)
        // console.log(this.self.info.table[tableIdex],sql,this.td.com.comattrs)
      }



      if (this.td.com.comevents.changeEvent) { //配置了sql语句 api 那么先执行 sql api  然后赋值

        console.log(this.td.com.comevents.changeEvent);
        this.changeEvent(this.microId);
      } else {
        let bl = this.getEvent(this.tableIndex, this.field, 'change') //从初始 js  获取 事件
        if (bl != null && typeof bl == 'function') {
          bl()
        }
        this.self.calc(this.trindex, this.tdindex);
        this.self.$forceUpdate() //强制刷新
        // this.self.settOption&&this.self.settOption&&this.self.settOption() //刷新下拉信息
      }
      let val = this.self.info.table[this.tableIndex].record[this.rindex][this.field]
      this.self.$emit(type, this.tableIndex, this.rindex, this.field, val);
    }
    if (type.indexOf('blur') > -1) {

      //离开的时候校验字段
      this.self.validateOneField(this.trindex, this.tdindex).then((res) => {
        if (res) {
          let bl = this.getEvent(this.tableIndex, this.field, 'blur')
          if (bl != null && typeof bl == 'function') {
            bl()
          }
        }
      })
      this.self.$forceUpdate()
      //			this.self.validateField(this.trindex,this.tdindex,this.td,this.rindex);
    }

    //		if(this.td.com.comevents.leftEvent){
    //			this[this.td.com.comevents.leftEvent]();
    //		}
    //		if(this.td.com.comevents.rightEvent){
    //			this[this.td.com.comevents.rightEvent]();
    //		}

    if (type.indexOf('dblclick') > -1) {
      console.log('333333333333333333', this.td.com.comevents)
      if (this.td.com.comevents.sql) {
        this.self.ceshi(`${this.td.com.comevents.sql}`)
      }
      // this.self.ceshi('sys.rep.ceshi1("哈哈哈哈")')
      //双击事件 调用双击
      if (this.td.com.comevents.doubleEvent) {
        this.doubleEvent = this.td.com.comevents.doubleEvent
        this[this.td.com.comevents.doubleEvent](0) //弹出框 需要 等弹出框关掉设置，所以用个类型 表示 设置还是弹出
      }
      if (
        this.td.com.comevents.dblvue == 'templateWindow.vue' &&
        this.td.com.comevents.dblcomId > 0
      ) {
        console.log('执行 templateWindow 弹窗')
        //执行 templateWindow 弹窗
        this.templateWindow()
      }

      if (this.td.com.comevents.dblvue == 'cellView.vue') {
        console.log('执行 cellView 弹窗')
        this.cellView();
      }

      if (this.td.com.comattrs.showType == 12) {
        //加特殊处理 因为子表中存在主表字段
        let $rindex = this.rindex;
        if (this.tableIndex == 0) {
          $rindex = 0;
        }
        this.self.fileList = this.self.info.table[this.tableIndex].record[$rindex][this.field];
        this.self.isBrowse = !this.td.com.comattrs.enable;
        this.self.show = "winSign";
      }
    }

    //		this[func]();//执行自定义事件
  }

  getacceptTimeNull() { //取消息时间
    if (this.td.com.comattrs.enable && this.self.info.table[this.tableIndex].record[this.rindex][this.field] == null) {
      console.log(this.self.acceptTime);
      this.self.info.table[this.tableIndex].record[this.rindex][this.field] = this.self.acceptTime;
      console.log(this.self.info.table[this.tableIndex].record);
      this.self.$forceUpdate()

    }
  }

  getUserName() {
    //取用户名

    if (this.td.com.comattrs.enable) {
      let userinfo = this.self.$store.state.user.info
      if (this.td.com.comattrs.showDetail) {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.id
      } else {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.name
        this.self.$forceUpdate()
      }
      this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
      this.self.settOption && this.self.settOption() //刷新下拉信息
    }
  }

  getUserNameNull() {
    //取用户名

    if (this.td.com.comattrs.enable && this.self.info.table[this.tableIndex].record[this.rindex][this.field] == null) {
      let userinfo = this.self.$store.state.user.info
      if (this.td.com.comattrs.showDetail) {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.id
      } else {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.name
        this.self.$forceUpdate()
      }
      this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
      this.self.settOption && this.self.settOption() //刷新下拉信息
    }
  }

  getUserDept() {
    //取用户部门
    if (this.td.com.comattrs.enable) {
      //    let userinfo = this.self.$store.state.user.info
      let dept;
      if (this.self.deptId) {
        dept = this.self.deptId;
      } else {
        dept = this.self.fill_dept_id;
      }

      if (this.td.com.comattrs.showDetail) {
        //      this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.deptId
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = dept;
        this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
        this.self.settOption && this.self.settOption() //刷新下拉信息
      } else {
        //      this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.deptName
        let tidx = this.tableIndex;
        let ridx = this.rindex;
        let fd = this.field;
        let infot = this.self.info.table;
        let thz = this;
        this.execApi('/dept/detail', {
          id: dept
        }).then((res) => {
          infot[tidx].record[ridx][fd] = res.info.name;
          thz.self.$forceUpdate() //双击后，数据变更了，可是页面没更新，用vue强制更新
          this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
          thz.self.settOption() //刷新下拉信息
        })
      }
    }
  }

  getUserDeptNull() {
    //取用户部门
    if (this.td.com.comattrs.enable && this.self.info.table[this.tableIndex].record[this.rindex][this.field] == null) {
      //    let userinfo = this.self.$store.state.user.info
      let dept;
      if (this.self.deptId) {
        dept = this.self.deptId;
      } else {
        dept = this.self.fill_dept_id;
      }

      if (this.td.com.comattrs.showDetail) {
        //      this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.deptId
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = dept;
        this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
        this.self.settOption && this.self.settOption() //刷新下拉信息
      } else {
        //      this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.deptName
        let tidx = this.tableIndex;
        let ridx = this.rindex;
        let fd = this.field;
        let infot = this.self.info.table;
        let thz = this;
        this.execApi('/dept/detail', {
          id: dept
        }).then((res) => {
          infot[tidx].record[ridx][fd] = res.info.name;
          thz.self.$forceUpdate() //双击后，数据变更了，可是页面没更新，用vue强制更新
          this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
          thz.self.settOption() //刷新下拉信息
        })
      }
    }
  }

  getUnit() { //unitId 用户单位
    if (this.td.com.comattrs.enable) {
      let userinfo = this.self.$store.state.user.info;
      if (this.td.com.comattrs.showDetail) {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.unitId;
      } else {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.unitName
        this.self.$forceUpdate()
      }
      this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
      this.self.settOption && this.self.settOption() //刷新下拉信息
    }
  }

  getUnitNull() { //unitName 用户单位
    if (this.td.com.comattrs.enable && this.self.info.table[this.tableIndex].record[this.rindex][this.field] == null) {
      let userinfo = this.self.$store.state.user.info;
      if (this.td.com.comattrs.showDetail) {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.unitId;
      } else {
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = userinfo.unitName
        this.self.$forceUpdate()
      }
      this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
      this.self.settOption && this.self.settOption() //刷新下拉信息
    }
  }

  getDateNull() {

    if (this.td.com.comattrs.enable && this.self.info.table[this.tableIndex].record[this.rindex][this.field] == null) {
      let dt = dateFormat();
      this.self.info.table[this.tableIndex].record[this.rindex][this.field] = dt;
    }
  }

  getDate() {
    if (this.td.com.comattrs.enable) {
      this.self.info.table[this.tableIndex].record[this.rindex][this.field] = dateFormat();
    }
  }

  // 自定义树
  customTree() {
    let dblParamIn = this.td.com.comevents.dblParamIn //把传入参数 的[] 字段内容替换掉
    let propParam = this.fieldReplace(dblParamIn)
    this.self.propsParam = JSON.parse(propParam)
    console.log('cmj弹窗参数*******')
    console.log(propParam)
    console.log(this.doubleEvent);
    this.self.show = this.doubleEvent
  }

  selectUser(type = 0, v) {
    //选择用户
    if (this.td.com.comattrs.enable) {
      let ids
      if (type == 0) {
        this.self.checkBoxShow = 1
        this.self.type = 2
        let dblParamIn = this.td.com.comevents.dblParamIn //把传入参数 的[] 字段内容替换掉
        let propParam = this.fieldReplace(dblParamIn)
        this.self.propsParam = JSON.parse(propParam)
        console.log('cmj弹窗参数*******')
        console.log(propParam)
        this.self.show = this.doubleEvent
      } else {
        if (this.td.com.comattrs.showDetail) {
          ids = v
            .map((obj) => {
              return obj.id
            })
            .join(',')
        } else {
          ids = v
            .map((obj) => {
              return obj[Object.keys(JSON.parse(this.td.com.comevents.dblParamOut))[0]] // 自定义返回参数
            })
            .join(',')
        }
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = ids
        console.log(this.self.info.table[this.tableIndex].record[this.rindex][this.field])
        this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
        this.self.settOption && this.self.settOption() //刷新下拉信息
      }
    }
  }

  selectDept(type, v) {

    //选择部门
    //this.td.com.comattrs.enable
    if (this.td.com.comattrs.enable) {
      let ids
      let names
      let selects
      if (type == 0) {
        this.self.checkBoxShow = 1
        this.self.type = 0
        let dblParamIn = this.td.com.comevents.dblParamIn //把传入参数 的[] 字段内容替换掉
        let propParam = this.fieldReplace(dblParamIn)
        this.self.propsParam = JSON.parse(propParam)
        console.log('cmj弹窗参数*******')
        console.log(propParam)
        this.self.show = this.doubleEvent
      }else if(type==1){
        //系统组件
         /*@description:遍历定义的数据返回对象，获取字段名和表的索引值，根据得到的数据动态给表字段进行赋值
         *@author: xuzhaoqian
         *@date: 2021-07-06 18:34:53
         *@version: V1.0.5
        */
        console.log(this.self.info.table[this.tableIndex])//表字段集合  fields:[] =>fieldName
        console.log(this.td.com.comevents.dblParamOut)//定义返回字段{"id":"[0:PUBLISH_ORG_ID]","name":"[0:PUBLISH_ORG]"}
        console.log(Object.keys(JSON.parse(this.td.com.comevents.dblParamOut))[0])
       
         let dblParamOut=JSON.parse(this.td.com.comevents.dblParamOut);
         let dblParamOutFileds=Object.keys(dblParamOut);
         dblParamOutFileds.forEach((paramField,pIndex) => {
           let paramName=null;
          let params = v
          .map((obj) => {
            paramName=dblParamOut[paramField].split(":")[1].replace("]","");
            return obj[Object.keys(JSON.parse(this.td.com.comevents.dblParamOut))[pIndex]] // 自定义返回参数
          })
          .join(',');
          this.self.info.table[this.tableIndex].record[this.rindex][paramName] = params
         });
        this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
        this.self.settOption && this.self.settOption() //刷新下拉信息
      } else {
        if (this.td.com.comattrs.showDetail) {
          ids = v
            .map((obj) => {
              return obj.id
            })
            .join(',')
          names = v
            .map((obj) => {
              return obj.name
            })
            .join(',')
          selects = {
            ID: ids,
            NAME: names
          }
          this.self.info.table[this.tableIndex].select[this.field].option.push(selects)
        } else {
          ids = v
            .map((obj) => {
              return obj[Object.keys(JSON.parse(this.td.com.comevents.dblParamOut))[0]] // 自定义返回参数
            })
            .join(',')
        }
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = ids

        this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
        this.self.settOption && this.self.settOption() //刷新下拉信息
      }
    }
  }

  selectFile(type = 0, v) { //上传附件
    if (this.td.com) {
      //获取 表名 主键值  以及字段  tableName fieldName isBrowse pkValue
      if (type == 0) {

        let dblParamIn = this.td.com.comevents.dblParamIn;
        this.self.isBrowse = !this.td.com.comattrs.enable;
        this.self.fileType = this.td.com.comattrs.name;
        this.self.pkValue = this.self.getPkeyValue(this.tableIndex, this.rindex);
        this.self.gcId = ""; //清空工程id 项目id
        this.self.xmId = "";
        if (dblParamIn) { //如果配置了附件上传的参数  ，那么取附件上传的参数
          console.log(this.self.info.table)

          let propParam = this.fieldReplace(dblParamIn); //tableName fieldName fieldValue gcId  xmId
          let pparam = JSON.parse(propParam);
          if (pparam.gcId) {
            this.self.gcId = pparam.gcId;
          }
          if (pparam.xmId) {
            this.self.xmId = pparam.xmId;
          }
          if (pparam.mid) {
            this.self.pkValue = pparam.mid;
          }
          if (pparam.isBrowse) {
            this.self.isBrowse = pparam.isBrowse;
          }
          if (pparam.disable == "0" || pparam.disable == 0 || pparam.disable == false) {
            return
          }
          this.self.$delete(pparam, 'disable');
          this.self.tableName = pparam.tableName
          this.self.fieldName = pparam.fieldName;
          this.self.fjParam = JSON.stringify(pparam);
          console.log(this.self.fjParam);
        } else {
          this.self.tableName = this.self.getTableName(this.tableIndex)
          this.self.fieldName = this.field
          // 可用是编辑  不可用是浏览

        }
        console.log(this.self.tableName)
        console.log(this.self.fieldName)
        console.log(this.self.pkValue)
        if (this.self.pkValue == null) {
          this.self.message('请先保存数据！', 3)
          return
        }
        this.self.show = this.doubleEvent
      } else {
        let vals

        if (Array.isArray(v)) {
          vals = v
            .map((obj) => {
              return obj.name
            })
            .join(',')
        } else {
          vals = v
        }
        this.self.info.table[this.tableIndex].record[this.rindex][this.field] = vals
        this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
        this.self.settOption && this.self.settOption() //刷新下拉信息
      }
    }
  }

  selectType(type = 0, v) {
    if (this.td.com.comattrs.enable) {
      //类型选择
      if (this.td.com) {
        //获取 表名 主键值  以及字段  tableName fieldName isBrowse pkValue
        if (type == 0) {
          this.self.pkValue = this.self.getPkeyValue(this.tableIndex, this.rindex)
          let showDetail = this.td.com.comevents.dblParamIn //把传入参数 的[] 字段内容替换掉
          let propParam = this.fieldReplace(showDetail)
          this.self.pparam = JSON.parse(propParam) //(new Function("return " + showDetail))();
          this.self.show = this.doubleEvent
        } else {
          let vals

          if (Array.isArray(v)) {
            vals = v
              .map((obj) => {
                return obj.name
              })
              .join(',')
          } else {
            vals = v
          }
          this.self.info.table[this.tableIndex].record[this.rindex][this.field] = vals
          this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
          this.self.settOption && this.self.settOption() //刷新下拉信息
        }
      }
    }
  }

  selectFunds(type = 0, v) { //资金类别
    if (this.td.com.comattrs.enable) {
      //类型选择
      if (this.td.com) {
        //获取 表名 主键值  以及字段  tableName fieldName isBrowse pkValue
        if (type == 0) {
          this.self.pkValue = this.self.getPkeyValue(this.tableIndex, this.rindex)
          let showDetail = this.td.com.comevents.dblParamIn //把传入参数 的[] 字段内容替换掉
          let propParam = this.fieldReplace(showDetail)
          this.self.pparam = JSON.parse(propParam) //(new Function("return " + showDetail))();
          this.self.show = this.doubleEvent
        } else {
          let vals

          if (Array.isArray(v)) {
            vals = v
              .map((obj) => {
                return obj.name
              })
              .join(',')
          } else {
            vals = v
          }
          this.self.info.table[this.tableIndex].record[this.rindex][this.field] = vals
          this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
          this.self.settOption && this.self.settOption() //刷新下拉信息
        }
      }
    }
  }

  selectMenu(type = 0, v) {

    if (this.td.com.comattrs.enable) {
      //类型选择
      if (this.td.com) {
        //获取 表名 主键值  以及字段  tableName fieldName isBrowse pkValue
        if (type == 0) {
          this.self.pkValue = this.self.getPkeyValue(this.tableIndex, this.rindex)
          console.log('报错？', this.td.com.comevents);
          let showDetail = this.td.com.comevents.dblParamIn //把传入参数 的[] 字段内容替换掉 
          let propParam = this.fieldReplace(showDetail)
          this.self.pparam = JSON.parse(propParam) //(new Function("return " + showDetail))();
          this.self.show = this.doubleEvent
        } else {
          let vals

          if (Array.isArray(v)) {
            vals = v
              .map((obj) => {
                return obj.name
              })
              .join(',')
          } else {
            vals = v
          }
          this.self.info.table[this.tableIndex].record[this.rindex][this.field] = vals

          console.log(this.self.info.table[this.tableIndex].record[this.rindex][this.field])
          this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
          this.self.settOption && this.self.settOption() //刷新下拉信息
        }
      }
    }
  }

  setValue(v) {
    //双击打开组件，组件返回值进行设值
    console.log(v)
    console.log(this.td.com.comevents.doubleEvent);
    this.self.show = null
    this.doubleEvent = null
    this[this.td.com.comevents.doubleEvent](1, v)
  }

  //解析二维数组，并赋值
  analysis(initParam) {
    for (let i = 0; i < initParam.length; i++) {
      let arr = initParam[i];
      for (let j = 0; j < arr.length; j++) {
        let tbl = arr[j];
        for (let key in tbl) {
          if (this.self.info.table[i].record[j]) {
            this.self.$set(this.self.info.table[i].record[j], key, initParam[i][j][key]);
          } else {
            this.self.info.table[i].record[j].push({});
            this.self.$set(this.self.info.table[i].record[j], key, initParam[i][j][key]);
          }
        }
      }
    }
  }

  autoRun() {
    //表单加载后自动运行
    //初始化 前台给的初始化信息
    //  console.log(JSON.stringify(this.self.tableset))
    this.events = []
    if (this.self.initParam != null) {
      this.analysis(this.self.initParam);
    }

    this.self.tableset.trs.forEach(($tr, $trindex) => {
      //遍历表单是否有自动运行的事件

      $tr.tds.forEach(($td, $tdindex) => {
        if ($td.com != null) {
          if ($td.com.comevents.autorun) {
            this.tr = $tr
            this.td = $td
            this.trindex = $trindex
            this.tdindex = $tdindex
            this.tableIndex = $td.com.comattrs.tableIdx
            this.rindex = $tr.rindex
            this.field = $td.com.comattrs.fieldName
            // this[$td.com.comevents.autorun]()
          }
        }
      })
    })

    if (this.self.info.initJs) {
      //如果有表单脚本 则运行表单脚本	权力最大最后运行，前面运行的结果都可以修改掉
      this.userEvent(this.self.info.initJs)
    }
  }

  getCode() {
    this.self.info.table[this.tableIndex].record[this.rindex][this.field] = '20200813001'
  }

  getOrd() {
    this.self.info.table[this.tableIndex].record[this.rindex][this.field] = this.tr.rindex + 1
  }

  afterSave() {
    if (this.self.info.afterSaveJs) {
      this.userEvent(this.self.info.afterSaveJs)
      this.self.$forceUpdate()
    }

  }

  beforeSend() {
    //如果返回整个函数的 resolve  就不用每个函数都写 resovle
    return new Promise((resolve) => {
      if (this.self.info.beforeSendJs) {
        //发送前判断是否有自定义设置
        this.userEvent(this.self.info.beforeSendJs).then((res) => {
          resolve(res)
          this.self.$forceUpdate()
        })
      } else {
        resolve(true)
      }
    })
  }

  // 系统参数替换
  sysParamReplace(paramIn) {
    if (paramIn.indexOf('[deptId]') > -1) {
      paramIn = paramIn.replace('[deptId]', this.self.deptId)
    }
    if (paramIn.indexOf('[userId]') > -1) {
      paramIn = paramIn.replace('[userId]', this.self.$store.state.user.info.id)
    }
    // 处理表单参数变量
    for (let key in this.self.info.param) {
      paramIn = paramIn.replace('[' + key + ']', this.self.info.param[key])
    }
    return paramIn
  }

  fieldReplace(dblParamIn, res = null) {
    dblParamIn = this.sysParamReplace(dblParamIn) //先替换系统变量

    for (let key in res) { //res  是sql 查询出来的结果
      if (dblParamIn.indexOf('[' + key + ']') > -1) {
        dblParamIn = dblParamIn.replace('[' + key + ']', res[key])
      }
    }
    for (let key in this.self.businessInfo) { //业务驱动新增的时候传过来的 工程id 项目id 等
      if (dblParamIn.indexOf('[' + key + ']') > -1) {
        dblParamIn = dblParamIn.replace('[' + key + ']', this.self.businessInfo[key])
      }
    }

    let regex = /(?<=\[)(\d+:){1,2}\w+(?=\])/g //用正则表达式 把 sql中的 参数取出来
    let params = dblParamIn.match(regex)
    let tableIdex = null
    let tfield = null
    if (params == null) {
      //如果正则表达  取出来的结果是  空  就赋值  []
      params = []
    }
    let obj = {}
    console.log(params);
    params.forEach((item, index) => {

      //参数取出后，组装参数
      let itemArr = item.split(':')
      //下拉框  切割 后  组装值
      tableIdex = parseInt(itemArr[0])
      let rind = null //获取行索引
      if (tableIdex == 0) {
        rind = 0
      } else {
        console.log(this);
        rind = this.rowIndex ? this.rowIndex : this.rindex ? this.rindex : 0;
        // rind = this.rowIndex?this.rowIndex:this.rowIndex


      }
      // console.log('xxxxxxxxxxx',rind)
      tfield = itemArr[itemArr.length - 1] //切割字段
      console.log(tableIdex, rind, tfield);
      if (!this.self.info.table[tableIdex].record[rind]) {
        rind = 0
      }
      let rval = this.self.info.table[tableIdex].record[rind][tfield] == undefined ? null : this.self.info.table[tableIdex].record[rind][tfield]; //undefined 会转成null 字符串转对象要用undefined  ，设置值 要用null
      console.log(123, rval);
      dblParamIn = dblParamIn.replace(
        "[" + item + "]",
        rval
      )

    })

    dblParamIn = dblParamIn.replace(
      /"null"/g,
      null
    )
    console.log(dblParamIn);

    console.log(typeof (dblParamIn));
    return dblParamIn
  }

  fieldReplaceNull(dblParamIn) { //存在null  就返回null
    dblParamIn = this.sysParamReplace(dblParamIn) //先替换系统变量

    let regex = /(?<=\[)(\d+:){1,2}\w+(?=\])/g //用正则表达式 把 sql中的 参数取出来
    let params = dblParamIn.match(regex)
    let tableIdex = null
    let tfield = null
    if (params == null) {
      //如果正则表达  取出来的结果是  空  就赋值  []
      params = []
    }
    let obj = {}
    let exitNull = false
    params.forEach((item, index) => {
      //参数取出后，组装参数
      let itemArr = item.split(':')
      //下拉框  切割 后  组装值
      tableIdex = parseInt(itemArr[0])
      let rind = null //获取行索引
      if (tableIdex == 0) {
        rind = 0
      } else {
        rind = this.rowIndex ? this.rowIndex : this.rindex ? this.rindex : 0;
        console.log('oooooooooo', this.self.info.table[this.tableIndex].record.length - 1 - this.tr.rindex + this.self.activetr)

      }
      tfield = itemArr[itemArr.length - 1] //切割字段
      console.log(this.self.info.table[tableIdex].record);

      var vall = this.self.info.table[tableIdex].record[rind][tfield];
      if (this.self.info.table[tableIdex].record[rind][tfield] == undefined || this.self.info.table[tableIdex].record[rind][tfield] == null || this.self.info.table[tableIdex].record[rind][tfield] == "") {
        exitNull = true;
      }
      let rval = this.self.info.table[tableIdex].record[rind][tfield] == undefined ? null : this.self.info.table[tableIdex].record[rind][tfield]; //undefined 会转成null 字符串转对象要用undefined  ，设置值 要用null
      dblParamIn = dblParamIn.replace(
        "[" + item + "]",
        rval
      )

    })
    if (exitNull) {
      return null;
    } else {
      return dblParamIn
    }
  }

  cellView() { //双击弹出表单		打开表单
    console.log(this.tableIndex, this.rindex)
    if (this.self.getPkeyValue(this.tableIndex, this.rindex) == null) {
      this.self.message('请先保存数据！', 3)
    }
    //		if (this.td.com.comattrs.enable) {
    let dblParamIn = this.td.com.comevents.dblParamIn;

    if (dblParamIn == null || dblParamIn == undefined) {
      return;
    }
    let pparam = JSON.parse(this.fieldReplace(dblParamIn));

    if (pparam.businessInfo != null) { //如果配置了公用的项目工程分包信息
      for (let key in pparam.businessInfo) {
        if (this.self.businessInfo == null) {
          this.self.businessInfo = {};
        }
        this.self.$set(this.self.businessInfo, key, pparam.businessInfo[key]);
      }
    }

    console.log(pparam)
    if (pparam.workId) {
      console.log(pparam)
      getWpIdByTable(pparam).then((res) => {
        this.self.$set(pparam, 'wpId', res.info);
        this.self.$set(pparam, 'nodeId', this.td.com.comattrs.enable ? 1 : 0);
        this.self.pparam = pparam;
        this.self.show = 'cellView';
      })
    } else {
      getRepId({
        classId: pparam.classId
      }).then((res) => {
        this.self.$set(pparam, 'wpId', res.info);
        this.self.$set(pparam, 'nodeId', this.td.com.comattrs.enable ? 1 : 0);
        this.self.pparam = pparam;
        this.self.show = 'cellView';
      })
    }
    //		}
  }

  setCellView(v) { //关闭表单
    console.log('关闭表单')
    this.self.show = null;

    if (v.table[0].record[0][v.table[0].pkey] == null || v.table[0].record[0][v.table[0].pkey] == 0) {
      return; //弹出表单无主键  说明不保存数据，那么就不能把弹出表单的值 赋给当前表单
    }
    let showDetail = this.td.com.comevents.dblParamOut; //获取输出
    if (showDetail == null || showDetail == undefined || !this.td.com.comattrs.enable) {
      return;
    }
    let out = JSON.parse(showDetail)
    let valset = []
    for (let key in out) {
      let ffield = key.substr(1, key.length - 2) //去掉首尾字符
      let itemArr = ffield.split(':') //冒号切割  成数组   0: key			取出表的索引  取出 数据rindex  取出 this.field
      let t = parseInt(itemArr[0])
      let r = isNaN(t) ? 0 : (v.table[t].record.length - 1);

      let f = itemArr[itemArr.length - 1]
      let fobj = {
        t: t,
        r: r,
        f: f
      }

      ffield = out[key].substr(1, out[key].length - 2) //去掉首尾字符
      itemArr = ffield.split(':') //冒号切割  成数组   0: key			取出表的索引  取出 数据rindex  取出 this.field
      t = parseInt(itemArr[0])
      r = 0
      if (isNaN(t) || t == 0) {
        r = 0
      } else {
        r = this.tr.rindex //双击目前设置为  后面添加记录  ，所以记录 点击行的 rindex  目前无效
      }
      f = itemArr[itemArr.length - 1]
      let tobj = {
        t: t,
        r: r,
        f: f
      };
      valset.push({
        f: fobj,
        t: tobj
      })
    }
    console.log(valset)

    if (this.tableIndex == -1) {
      //按钮点击弹窗的窗体，只要解析from的表对象就行
      for (let i = 0; i < valset.length; i++) {
        let fobj = valset[i].f;
        let tobj = valset[i].t;

        let val = v.table[fobj.t].record[0][fobj.f];


        console.log(fobj, tobj, val, showDetail)
        showDetail = showDetail.replace('[' + fobj.t + ':' + fobj.f + ']', tobj.f)
        showDetail = showDetail.replace('[' + tobj.f + ']', val)
      }
      out = JSON.parse(showDetail)
      console.log(out)
      return
    }


    let valobj = {}; //把数据 按表 组装成  对象   0：[{},{},{}]  1:[{},{},{}]  2:[{},{},{}]
    for (let i = 0; i < valset.length; i++) {
      let ob = valset[i].t;
      // console.log(ob);
      if (valobj[ob.t] == null) {
        this.self.$set(valobj, ob.t.toString(), []);
        valobj[ob.t].push(valset[i]);
      } else {
        valobj[ob.t].push(valset[i]);
      }
    }
    console.log(valobj);
    console.log(Object.keys(valobj));
    Object.keys(valobj).forEach((key) => {
      if (key == "0") {
        for (let i = 0; i < valobj[key].length; i++) {
          var fobj = valobj[key][i].f;
          var tobj = valobj[key][i].t;
          if (fobj.t > 0) { //双击打开表单的返回数据是子表，写到当前双击表单的主表  取第一条记录，否则不处理，以后可以拓展合并到一条，
            if (v.table[fobj.t].record.length = 1) {
              let val = v.table[fobj.t].record[0][fobj.f];
              this.self.info.table[tobj.t].record[tobj.r][tobj.f] = val;
            } else { //如果压缩  写这里

            }
          } else { //主表对主表设值
            let val = v.table[fobj.t].record[fobj.r][fobj.f]; //双击打开表单的返回值
            console.log(val);
            this.self.info.table[tobj.t].record[tobj.r][tobj.f] = val;


          }
        }
      } else { //对子表设置  获取要设值的子表索引，并找到该子表是否要进行唯一性校验  ，
        let hasadd = false;
        let tbindex = parseInt(key);
        let myKey = null
        console.log(tbindex)
        //info.table[0].fields[2].uniqRule
        let pkey = null;
        console.log(this.self.info.table[tbindex]);
        for (let i = 0; i < this.self.info.table[tbindex].fields.length; i++) { //判断是否 配置了唯一键
          let tfield = this.self.info.table[tbindex].fields[i];
          if (tfield.uniqRule) {
            pkey = tfield.uniqRule.substring(5);
            break;
          }
        }

        //设置  tableIndex的值 默认0 ，取返回子表的第一次遇到的多条记录的rindex为参考，其它一律用0代替
        let tableIndex = 0;
        for (let o = 0; o < valobj[key].length; o++) { //遍历  0：[{},{},{}]  1:[{},{},{}]  2:[{},{},{}]
          let fobj = valobj[key][o].f;
          if (v.table[fobj.t].record.length > 1) {
            tableIndex = fobj.t;
            break;
          }
        }
        console.log(tableIndex);
        for (let kk = 0; kk < v.table[tableIndex].record.length; kk++) { //根据返回表单的数据 根据双击配置的返回格式 ，组装数据
          let obj = {}; //组装obj
          console.log(valobj, key);
          for (let o = 0; o < valobj[key].length; o++) { //遍历  0：[{},{},{}]  1:[{},{},{}]  2:[{},{},{}]
            let fobj = valobj[key][o].f;
            let tobj = valobj[key][o].t;
            let r = 0;
            if (fobj.t == tableIndex) {
              r = kk;
            }
            this.self.$set(obj, 'indexForSelect', kk);
            this.self.$set(obj, tobj.f, v.table[tableIndex].record[r][fobj.f]);
          }
          // if(v.table[1] && v.table[1].record[0] && v.table[0].record[0].DANGER_ID == v.table[1].record[0].DANGER_ID){

          //   let name = ''
          //   for(let i=0;i<v.table[1].record.length;i++){
          //     name +=  v.table[1].record[i].CONTROL_MEASURE_CONTENT
          //   }
          //   obj.GKCS = name
          //   obj.DANGER_NAME = v.table[0].record[0].DANGER_NAME
          //   obj.WORK_PLAN_ID = v.table[0].record[0].WORK_PLAN_ID
          //   obj.WORK_PLAN_TYPE = v.table[0].record[0].WORK_PLAN_TYPE
          // }
          if (v.table[1] && v.table[1].record && v.table[1].record.length > 1) {
            let name = 0
            for (let i = 0; i < v.table[1].record.length - 1; i++) {
              for (let j = 0; j < Object.keys(v.table[1].record[0]).length; j++) {
                if (Object.keys(v.table[1].record[i])[j] == Object.keys(v.table[1].record[i + 1])[j]) {
                  if (v.table[1].record[i][Object.keys(v.table[1].record[i])[j]] != v.table[1].record[i + 1][Object.keys(v.table[1].record[i + 1])[j]]) {
                    if (!(escape(v.table[1].record[i][Object.keys(v.table[1].record[i])[j]]).indexOf("%u") < 0 && escape(v.table[1].record[i + 1][Object.keys(v.table[1].record[i + 1])[j]]).indexOf("%u") < 0)) {
                      name = v.table[1].record[i][Object.keys(v.table[1].record[i])[j]] + v.table[1].record[i + 1][Object.keys(v.table[1].record[i + 1])[j]]
                    }
                  }
                }
              }
            }
            for (let k = 0; k < Object.keys(obj).length; k++) {
              // obj[Object.keys(obj)][k]
              if (!(escape(obj[Object.keys(obj)[k]]).indexOf("%u") < 0)) {
                // console.log(name);
                obj[Object.keys(obj)[k]] = name
              }
            }
          }
          console.log(obj);
          //判断  是否有唯一键  ，如果有就验证
          if (pkey) {

            console.log(pkey);

            let has = false;
            for (let k = 0; k < this.self.info.table[tbindex].record.length; k++) {
              var record = this.self.info.table[tbindex].record[k];
              if (record[pkey] == obj[pkey]) {
                has = true;
                break;
              }
            }
            if (!has) {
              for (let nn = 0; nn < this.self.info.table[tbindex].record.length; nn++) { //删除空记录
                let sob = this.self.info.table[tbindex].record[nn];
                console.log(JSON.stringify(sob));

                if (JSON.stringify(sob) == "{}") {
                  this.self.info.table[tbindex].record.splice(nn, 1);
                }
              }
              this.self.info.table[tbindex].record.push(obj);
              // console.log(v.table[0].select);
              if (v.table[0].select) {
                // console.log(Object.keys(v.table[0].select));
                for (let i = 0; i < Object.keys(v.table[0].select).length; i++) {
                  // console.log(Object.keys(v.table[0].select)[i]);
                  this.self.info.table[tbindex].select[Object.keys(v.table[0].select)[i]] = v.table[0].select[Object.keys(v.table[0].select)[i]]
                }
                // this.self.info.table[tbindex].select = v.table[0].select
              }
              hasadd = true;
            } else {
              // console.log(obj)
              // this.self.info.table[tbindex].record = [obj];
              for (let index in this.self.info.table[tbindex].record) {

                let item = this.self.info.table[tbindex].record[index]

                if (item[pkey] == obj[pkey]) {
                  this.self.$set(this.self.info.table[tbindex].record, index, {
                    ...item,
                    ...obj
                  })
                }
                // if(index == obj.indexForSelect){
                // item = {...item,...obj}

                // }
              }
              console.log(this.self.info.table[tbindex].record)
              // hasadd = true;
              // this.self.info.table[tbindex].record.map(item=>{
              //     if(item[pkey] == obj[pkey]){
              //         item.
              //     }
              // })

            }
          } else { //不验证

            console.log(77777777)
            let tr = this.self.tableset.trs[this.self.activetr]
            if (!tr.tds[this.self.activetd].com.comattrs.multiSelect) {
              console.log(888888, tr.rindex)
              this.setTableRecord(tbindex, tr.rindex, obj);
              // this.self.$set(this.self.info.table[tbindex].record,tr.rindex,{...item,...obj})
            } else {
              // console.log(this.self.info.table[tbindex].record,obj)
              for (let nn = 0; nn < this.self.info.table[tbindex].record.length; nn++) { //删除空记录
                let sob = this.self.info.table[tbindex].record[nn];
                if (JSON.stringify(sob) == "{}") {
                  this.self.info.table[tbindex].record.splice(nn, 1);
                }
              }
              this.self.info.table[tbindex].record.push(obj);
              // this.self.info.table[tbindex].record = [obj];
              // console.log(tbindex);
              // console.log(v.table[0].select);
              if (v.table[0].select) {
                // console.log(Object.keys(v.table[0].select));
                for (let i = 0; i < Object.keys(v.table[0].select).length; i++) {
                  // console.log(Object.keys(v.table[0].select)[i]);
                  this.self.info.table[tbindex].select[Object.keys(v.table[0].select)[i]] = v.table[0].select[Object.keys(v.table[0].select)[i]]
                }
                // this.self.info.table[tbindex].select = v.table[0].select
              }
              hasadd = true;
            }

          }
        }
        if (v.table && v.table[0].record && v.table[0].record[0] && v.table[0].record[0]) {
          // alert(this.self.info.table[tbindex].record.length -1)
          // this.self.info.table[2].record[this.self.info.table[tbindex].record.length -1].DANGER_NAME = v.table[0].record[0].DANGER_NAME
          let aa = Object.keys(v.table[0].record[0])
          let bb = Object.keys(this.self.info.table[2].record[0])
          let cc = []
          for (let i = 0; i < aa.length; i++) {
            this.self.info.table[2].record[this.self.info.table[tbindex].record.length - 1][aa[i]] = v.table[0].record[0][aa[i]]
          }
          // for(let i=0;i<aa.length;i++){
          //   for(let j=0;j<bb.length;j++){
          //     if(aa[i]==bb[j]){
          //       cc.push(i)
          //     }
          //   }
          // }
          // console.log(cc);
          // for(let l=0;l<cc.length;l++){
          //   this.self.info.table[2].record[0].aa[cc[l]] = v.table[0].record[0].aa[cc[l]]
          // }
          // 如果新带进来的对象中的键在self.table中不存在，那就给他动态加进去。CC是记录新带进来对象的和原来的不重复的
        }
        // console.log(11111111111111,this.self.info);

        //  		for(let i=0;i<this.self.tableset.trs.length;i++){
        //  			let tr = this.self.tableset.trs[i];
        //  			for(let j=0;j<tr.tds.length;j++){
        //  				let td = tr.tds[j];
        //  				if(td.com){
        //  					if(td.com.comattrs.tableIdx == tbindex){//找到 tableset 中的 td.com.comattrs.tableIdx  接着按 子表是否有唯一键 设置 判断，
        //  						let pkey = this.self.getUniqKey(i); //获取唯一键
        //				        let tdindex = null;
        //
        //				        if(pkey){//设置了多行 需要验证的唯一键
        //									let arr = pkey.split('--');
        //									pkey = arr[0];
        //									tdindex = arr[1];
        //									//返回值遍历
        //								}
        //									//设置  tableIndex的值 默认0 ，取返回子表的第一次遇到的多条记录的rindex为参考，其它一律用0代替
        //									let tableIndex = 0;
        //									for(let o=0;o<valobj[key].length;o++){//遍历  0：[{},{},{}]  1:[{},{},{}]  2:[{},{},{}]
        //					    			let fobj = valobj[key][o].f;
        //					    			if(v.table[fobj.t].record.length>1){
        //					    				tableIndex = fobj.t;
        //					    				break;
        //					    			}
        //					    		}
        //									//设置  输出json 中的rindex 的值
        //									console.log(v.table[tableIndex].record.length);
        //
        //									for(let kk=0;kk<v.table[tableIndex].record.length;kk++){//根据返回表单的数据 根据双击配置的返回格式 ，组装数据
        //										let obj = {};//组装obj
        //										for(let o=0;o<valobj[key].length;o++){//遍历  0：[{},{},{}]  1:[{},{},{}]  2:[{},{},{}]
        //					    				let fobj = valobj[key][o].f;
        //					    				let tobj = valobj[key][o].t;
        //					    				let r = 0;
        //					    				if(fobj.t == tableIndex){
        //					    					r = kk;
        //					    				}
        //					    				this.self.$set(obj,tobj.f,v.table[tableIndex].record[r][fobj.f]);
        //					    			}
        //				    				//判断  是否有唯一键  ，如果有就验证
        //										if(pkey&&tdindex){
        //											let has = false;
        //					        		for(let k=0;k<this.self.info.table[tbindex].record.length;k++){
        //					        			let record = this.self.info.table[tbindex].record[k];
        //					        			if(record[pkey] == obj[pkey]){
        //					        				has = true;
        //					        				break;
        //					        			}
        //					        		}
        //					        		if(!has){
        //				        				for(let nn = 0 ; nn < this.self.info.table[tbindex].record.length; nn++){//删除空记录
        //				        					let sob = this.self.info.table[tbindex].record[nn];
        //				        					if(JSON.stringify(sob) =="{}"){
        //				        						this.self.info.table[tbindex].record.splice(nn,1);
        //				        					}
        //				        				}
        //				        				this.self.info.table[tbindex].record.push(obj);
        //				        				hasadd = true;
        //					        		}
        //										}else{//不验证
        //
        //											for(let nn = 0 ; nn < this.self.info.table[tbindex].record.length; nn++){//删除空记录
        //			        					let sob = this.self.info.table[tbindex].record[nn];
        //			        					if(JSON.stringify(sob) =="{}"){
        //			        						this.self.info.table[tbindex].record.splice(nn,1);
        //			        					}
        //			        				}
        //			        				this.self.info.table[tbindex].record.push(obj);
        //			        				hasadd = true;
        //										}
        //
        //									}
        //								break;//已经找到对应的td的tbleIndex ，跳出循环
        //  					}
        //  				}
        //  			}
        //  		}
        if (hasadd) { //刷新tableset，重新渲染
          this.self.setTableSetNouserEvent();
        }
      }
    });

  }

  setSign(v) { //设置签名
    if (this.td.com.comattrs.enable) {
      //加特殊处理 因为子表中存在主表字段
      let $rindex = this.rindex;
      if (this.tableIndex == 0) {
        $rindex = 0;
      }
      this.self.info.table[this.tableIndex].record[$rindex][this.field] = v;
      this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
    }
    this.self.show = null;
  }

  templateWindow() {
    //判断双击是否是子表    onlyOne == true  传当前点击行的字段值  返回的记录  合并成一条记录    ，onlyOne == false  那么 要传   子表的多条记录
    if (this.td.com.comattrs.enable) {
      let showDetail = this.td.com.comevents.dblParamIn //把传入参数 的[] 字段内容替换掉
      let propParam = this.fieldReplace(showDetail)
      this.self.pparam = JSON.parse(propParam) //(new Function("return " + showDetail))();
      this.self.show = 'templateWindow'
    }
  }

  setRecordOld(v, out = null, microId) {
    //templateWindow
    let isbtnclick = true; //判断是否表单双击 还是按钮点击
    if (out == null) {
      isbtnclick = false;
      let showDetail = this.td.com.comevents.dblParamOut
      out = JSON.parse(showDetail)
    }

    let valset = []
    for (let key in out) {
      let tfield = out[key].substr(1, out[key].length - 2) //去掉首尾字符
      let itemArr = tfield.split(':') //冒号切割  成数组   0: key			取出表的索引  取出 数据rindex  取出 this.field
      let t = parseInt(itemArr[0])

      let r = 0
      if (isNaN(t) || t == 0) {
        r = 0
      } else {
        r = this.tr.rindex
      }
      let f = itemArr[itemArr.length - 1]
      valset.push({
        t: t,
        r: r,
        f: f,
        key: key
      })
    }
    // console.log(valset)
    //  valset 输出字段
    if (!isbtnclick) { //表单双击
      //表单双击出来的 out  在td.com.comevents.dblParamOut
      if (this.tableIndex == 0 || (this.tableIndex == 1 && this.td.com.comevents.onlyOne)) {
        //主表 或者 子表取值放到单条记录 那么 取出来的数据如果是多条就要合并记录
        valset.forEach((s) => {
          let key = s.key
          let keyVal = null
          v.forEach((val) => {
            //把v的数组里这个字段合并起来
            if (val[key] != undefined) {
              if (keyVal == null) {
                keyVal = val[key]
              } else {
                keyVal = keyVal + ',' + val[key]
              }
            }

          })
          // console.log(v,keyVal)
          this.self.$set(this.self.info.table[s.t].record[s.r], s.f, keyVal)
        })
        // console.log('inputchangeinputchangeinputchangeinputchange')
        // this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件  主表设置 change事件 ，子表等要用的时候触发
        // this.self.settOption&&this.self.settOption() //刷新下拉信息
      }

      if (this.tableIndex != 0 && !this.td.com.comevents.onlyOne) { //子表多记录 插入多行
        //插入多条记录

        let pkey = this.self.getUniqKey(this.trindex); //获取唯一键
        let j = null;

        if (pkey) { //设置了多行 需要验证的唯一键
          let arr = pkey.split('--');
          pkey = arr[0];
          j = arr[1];
        }
        let hasadd = false;
        let kk = null;
        if (pkey) {
          for (let tt = 0; tt < valset.length; tt++) { //从valset找出 返回值 中 ，唯一键 对应的 返回值中的字段
            if (valset[tt].f == pkey) { //valset 中的f 就是要校验的 pkey ，valset中的key 是返回值的字段
              kk = valset[tt].key;
            }
          }
        }

        for (let i = 0; i < v.length; i++) { //遍历 返回的记录
          if (pkey && j && v[i][kk]) {
            let has = false;
            let kIndex = 0
            for (let k = 0; k < this.self.info.table[this.tableIndex].record.length; k++) {
              let record = this.self.info.table[this.tableIndex].record[k];
              if (record[pkey] == v[i][kk]) {
                has = true;
                kIndex = k;
                break
              }
            }


            // console.log('ccccccccccc')
            let obj = {};
            for (let z = 0; z < valset.length; z++) {
              let s = valset[z]; // 表记索引录要重新设定
              let temprindex = s.r;
              if (s.t == this.tableIndex) { //如果输出的是当前双击单元格的子表  ，那么增加记录，否则全部过滤掉垃圾数据
                this.self.$set(obj, s.f, v[i][s.key]);
              }
            }

            if (JSON.stringify(obj) != "{}") {
              //判断是否有空记录，有的话，先把空记录填满 ，然后在后面添加新的记录

              for (let nn = 0; nn < this.self.info.table[this.tableIndex].record.length; nn++) {
                let sob = this.self.info.table[this.tableIndex].record[nn];

                if (JSON.stringify(sob) == "{}") {
                  this.self.info.table[this.tableIndex].record.splice(nn, 1);
                } else {
                  let rcordNull = true;
                  for (let keyf in sob) {
                    if (sob[keyf] != null) {
                      rcordNull = false
                    }
                  }
                  if (rcordNull) {
                    this.self.info.table[this.tableIndex].record.splice(nn, 1);
                  }
                }
              }
              if (!has) {
                this.self.info.table[this.tableIndex].record.push(obj);
                //更新当前坐标对象
                this.rowIndex = this.self.info.table[this.tableIndex].record.length - 1
                // console.log(JSON.stringify(obj));
                hasadd = true;
              } else {
                this.setTableRecord(this.tableIndex, kIndex, obj);
                this.rowIndex = kIndex
              }
            }


            // console.log('11111111111111111',this.tr,this.self.tableset)
          } else { //不需要验证
            let obj = {};
            for (let z = 0; z < valset.length; z++) {
              let s = valset[z]; // 表记索引录要重新设定
              let temprindex = s.r;
              if (s.t == this.tableIndex) { //如果输出的是当前双击单元格的子表  ，那么增加记录，否则全部过滤掉垃圾数据
                this.self.$set(obj, s.f, v[i][s.key]);
              }
            }

            if (JSON.stringify(obj) != "{}") {
              //如设置了单行模式则只修改本行，否则添加新的一行

              let tr = this.self.tableset.trs[this.self.activetr]

              // console.log(tr)
              if (!tr.tds[this.self.activetd].com.comattrs.multiSelect) {
                // console.log(888888,tr.rindex)
                this.setTableRecord(this.tableIndex, tr.rindex, obj);
                this.rowIndex = this.tr.rindex
              } else {
                let adnew = false; //判断是否有空记录，有的话，先把空记录填满 ，然后在后面添加新的记录
                for (let nn = 0; nn < this.self.info.table[this.tableIndex].record.length; nn++) {
                  let sob = this.self.info.table[this.tableIndex].record[nn];
                  if (JSON.stringify(sob) == "{}") {
                    this.self.info.table[this.tableIndex].record.splice(nn, 1);
                  } else {
                    let rcordNull = true;
                    for (let keyf in sob) {
                      if (sob[keyf] != null) {
                        rcordNull = false
                      }
                    }
                    if (rcordNull) {
                      this.self.info.table[this.tableIndex].record.splice(nn, 1);
                    }
                  }
                }
                if (!adnew) {
                  this.self.info.table[this.tableIndex].record.push(obj);

                  this.rowIndex = this.self.info.table[this.tableIndex].record.length - 1
                  hasadd = true;
                  console.log('11111111111111111', this.tr)
                  // this.tr.rindex = this.self.info.table[this.tableIndex].record.length-1
                  // this.tr = this.self.tableset.trs[]
                  // this.td = this.self.inf.setRecord
                  // console.log(JSON.stringify(obj));
                }
              }

            }
          }
        }
        if (hasadd) { //刷新tableset，重新渲染
          this.self.setTableSetNouserEvent();
        }

      }
      this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td, microId); //触发字段change事件  主表设置 change事件 ，子表等要用的时候触发
      this.self.settOption && this.self.settOption() //刷新下拉信息
    } else {
      //按钮点击出来的 out参数  从表单传入
      if (!this.self.comParam) {
        this.message("请求参数为空", 3)
        return
      }
      valset.forEach((s) => {
        let key = s.key
        let keyVal = null
        v.forEach((val) => {
          //把v的数组里这个字段合并起来
          if (keyVal == null) {
            keyVal = val[key]
          } else {
            keyVal = keyVal + ',' + val[key]
          }
        })
        this.self.comParam = this.self.comParam.replace("[" + key + "]", keyVal)
        //this.self.$set(this.self.info.table[s.t].record[s.r], s.f, keyVal)
      })
      // this.runEvent('inputchange', this.trindex, this.tdindex, this.tr, this.td); //触发字段change事件
      // this.self.settOption && this.self.settOption() //刷新下拉信息
      // 开始 后端请求
      let method = 'post'
      let type = ''
      let form = new FormData()
      let params = ''
      // btnIndex变量
      if (this.self.info.button[0].contentType === 1) {
        type = 1
        for (let i in JSON.parse(this.self.comParam)) {
          form.append(i, JSON.parse(this.self.comParam)[i])
        }
        params = form
      } else {
        type = 2
        params = this.self.comParam
      }
      userDefinedApi(params, this.self.info.button[0].url, method, type).then((res) => {
        console.log(res)
        if (res.code === '200') {
          this.self.$message({
            message: res.msg,
            type: 'success'
          });
        } else {
          this.self.$message({
            message: res.msg,
            type: 'error'
          });
        }
      });
    }
    this.self.show = null
  }

  setRecordNew(v) {
    console.log('setRecordNew')
    //table:0,record:{field:field},single:true,merge:false,clear:false;  按新的配置方式/
    let showDetail = this.td.com.comevents.dblParamOut;
    let arrs = showDetail.split(';')
    for (let i = 0; i < arrs.length; i++) {
      let jsonO = JSON.parse(arrs[i]);

      if (jsonO.merge) { //判断是否合并
        let recordO = {};
        for (let key in jsonO.record) {
          let fkey = jsonO.record[key]
          let fval = null;
          if (fkey.indexOf('count') > -1) {
            fval = v.length;
          } else {
            for (let j = 0; j < v.length; j++) {
              if (v == null) {
                fval = v[j][fkey];
              } else {
                fval = fval + "," + v[j][fkey]
              }

            }
          }
          this.self.$set(recordO, key, fval)
        }

        if (jsonO.table == 0) { //主表一个个赋值
          for (let keyt in recordO) {
            this.self.$set(this.self.info.table[jsonO.table].record, keyt, recordO[keyt]);
          }
        } else { //子表，判断是否要清除记录 还要判断是否存在唯一键 ，合并记录不需要判断唯一键
          if (jsonO.clear) {
            this.self.info.table[jsonO.table].record = [];
          }
          this.self.info.table[jsonO.table].record.push(recordO);
        }
      } else {
        if (jsonO.clear) {
          this.self.info.table[jsonO.table].record = [];
        } else {
          //清空当前子表的空记录
          if (jsonO.table > 0) {
            for (let nn = 0; nn < this.self.info.table[jsonO.table].record.length; nn++) {
              let sob = this.self.info.table[jsonO.table].record[nn];
              if (JSON.stringify(sob) == "{}") {
                this.self.info.table[jsonO.table].record.splice(nn, 1);
              } else {
                let rcordNull = true;
                for (let keyf in sob) {
                  if (sob[keyf] != null) {
                    rcordNull = false
                  }
                }
                if (rcordNull) {
                  this.self.info.table[jsonO.table].record.splice(nn, 1);
                }
              }
            }
          }
        }

        //遍历选中的记录，
        for (let j = 0; j < v.length; j++) {
          let recordO = {};
          for (let key in jsonO.record) { //读取 表单字段  和 组件字段的 对应关系
            let fkey = jsonO.record[key]
            let val = null;
            if (fkey.indexOf('count') > -1) { //如果配置了 count 关键字  那么 读取记录数
              val = v.length;
            } else {
              val = v[j][fkey];
            }
            this.self.$set(recordO, key, val)
          }
          if (jsonO.table == 0) { //如果是主表 ，那么就取第一条记录
            if (j == 0) {
              for (let keyt in recordO) {
                this.self.$set(this.self.info.table[jsonO.table].record[0], keyt, recordO[keyt]);
              }
              console.log(this.self.info.table[jsonO.table].record[0]);
            }
          } else { //子表，判断是否要清除记录 还要判断是否存在唯一键 ，合并记录不需要判断唯一键
            if (jsonO.clear) {
              this.self.info.table[jsonO.table].record.push(recordO);
            } else { //判断是否有唯一键设置
              let pkey = null;
              //查找当前子表的pkey  唯一键            info.table[0].fields[0].uniqRule
              for (let f = 0; f < this.self.info.table[jsonO.table].fields.length; f++) {
                let $field = this.self.info.table[jsonO.table].fields[f];
                if ($field.uniqRule.indexOf('pkey:') > -1) {
                  pkey = $field.uniqRule.substring(5)
                  break;
                }
              }
              if (pkey) { //存在pkey
                let has = false;
                for (let k = 0; k < this.self.info.table[jsonO.table].record.length; k++) {
                  let record = this.self.info.table[jsonO.table].record[k];
                  if (record[pkey] == recordO[pkey]) {
                    has = true;
                  }
                }
                if (!has) {
                  this.self.info.table[jsonO.table].record.push(recordO);
                }
              } else { //不存在pkey  就全部插入
                this.self.info.table[jsonO.table].record.push(recordO);
              }
            }
          }
        }
      }
    }
    this.self.show = null
  }

  setRecord(v, out = null, microId) { //表单 按钮点击，输出参数 不写在 td.com.comevents.dblParamOut 所以输出参数由按钮传入 v是弹出窗口传入的值
    // alert(microId)
    console.log('v,out', v, out)
    if (v.length == 0) {
      this.self.message("没有选中记录！", 3)
      return;
    }
    if (out) {
      this.setRecordOld(v, out);
    } else {
      let showDetail = this.td.com.comevents.dblParamOut;
      console.log(showDetail);
      if (showDetail.indexOf("table") > -1 && showDetail.indexOf("record") > -1) {
        this.setRecordNew(v)
      } else {
        this.setRecordOld(v, out, microId);
      }
    }
  }

  getEvent(table, field, eventName) {
    for (let i = 0; i < this.events.length; i++) {
      if (this.events[i].name == table + '-' + field) {
        return this.events[i].eventName.func
      }
    }
    return null
  }

  // [sS][uU][mM]\(.*\)  (?<=[sS][uU][mM]\()(.*)(?=\))  正则

  //通用方法
  todate(tdate, type = 'd') {
    //日期字符转日期
    let d = tdate.replace(new RegExp('-', 'gm'), '/')
    let res
    if (type == 'y') {
      res = new Date(d).getTime() / 1000 / 60 / 60 / 24 / 365 //得到毫秒数
    }
    if (type == 'm') {
      res = new Date(d).getTime() / 1000 / 60 / 60 / 24 / 30 //得到毫秒数
    }
    if (type == 'd') {
      res = new Date(d).getTime() / 1000 / 60 / 60 / 24 //得到毫秒数
    }
    if (type == 'h') {
      res = new Date(d).getTime() / 1000 / 60 / 60 //得到小时
    }
    if (type == 'mi') {
      res = new Date(d).getTime() / 1000 / 60 //得到分
    }
    return res
  }

  sql(sql, microId) {
    //查询sql
    return new Promise((resolve, reject) => {

      sql = encodeURIComponent(sql.trim())
      let sqlArr = []
      let n = 100
      for (let i = 0, l = sql.length; i < l / n; i++) {
        let a = sql.slice(n * i, n * (i + 1))
        sqlArr.push(encrypt(a))
      }

      let param = sqlArr
      let params = { sql: param, microId: microId }
      wpgetData(params).then((res) => {
        return resolve(res)
      })
    })
  }

  execsql(param) {
    //执行sql
    return new Promise((resolve, reject) => {
      wpsaveData(param).then((res) => {
        return resolve(res)
      })
    })
  }

  enc(str) {
    //加密字符串
    return encrypt(str)
  }

  user() {
    return this.self.$store.state.user.info

    return new Promise((resolve) => {
      resolve(true)
    })
  }

  execApi(url, param, type = 0) {
    return execApi(url, param, type)
  }

  //click blur dblclick
  setEvent(table, field, eventName, func) {
    let ev = {
      name: table + '-' + field,
      eventName: {
        func: func
      }
    }
    this.events.push(ev)
  }

  setTableRecord(tbindex, rindex, obj) {
    console.log(this.self.info.table[tbindex].record.length)
    console.log(rindex)
    console.log(obj)
    console.log('2222222222222')
    console.log(this.self.info.table[tbindex].record.length, rindex, obj)
    // console.log(this.self.info.table[tbindex].record[rindex])
    if (obj == null || obj == undefined) {
      return;
    }
    let rs = this.self.info.table[tbindex].record[rindex];
    console.log('22222', rs)
    // rs == null
    if (!rs) {
      this.self.info.table[tbindex].record.push({});
    }

    for (let key in obj) {
      console.log(obj[key])
      this.self.$set(this.self.info.table[tbindex].record[rindex], key, obj[key])
    }
    console.log(this.self.info.table[tbindex].record[rindex])
    console.log(this.self.info.table[tbindex])
    console.log(this.self.info.table[tbindex].record.length, rindex)

  }

  changeEvent(microId) {
    let str = this.td.com.comevents.changeEvent;
    let sql = null;
    let uniq = null;
    let clear = false;
    let tbindex = -1;
    let canRun = true;
    if (str) { //可以加 规则  满足 rule
      let strarr = str.split(";");
      for (let t = 0; t < strarr.length; t++) {
        let tstr = strarr[t];
        if (tstr.indexOf("sql:") > -1) {
          sql = tstr.substr(4);
        }
        if (tstr.indexOf("uniq:") > -1) {
          uniq = tstr.substr(5);
        }
        if (tstr.indexOf("clear:") > -1) {
          clear = tstr.substr(6) === 'true';
        }
        if (tstr.indexOf("tbindex:") > -1) {
          tbindex = tstr.substr(8);
        }
      }
    }

    //做校验   按[] 切割出 变量  然后按  类型进行校验
    if (uniq) {
      canRun = false; //如果要验证，就设定 不可运行
      let uniqf = this.fieldReplaceNull(uniq);
      if (uniqf) {
        let func = new Function('return ' + uniqf);
        canRun = func();
      }
    }

    if (sql && canRun) {
      sql = this.fieldReplaceNull(sql);
      if (sql) {
        this.sql(sql, microId).then((res) => {
          if (res.success) { //info[0].NAME
            if (clear) {
              this.self.info.table[tbindex].record = [];
            }

            if (tbindex == 0) {
              let obj = res.info[0];
              this.setTableRecord(tbindex, 0, obj);
            } else { //子表要多条记录
              let joinObj = {}
              for (let i = 0; i < res.info.length; i++) {
                Object.keys(res.info[i]).map(key => {
                  if (!joinObj[key] || joinObj[key] == null) joinObj[key] = res.info[i][key]
                  else {
                    joinObj[key] = joinObj[key] + ',' + res.info[i][key]
                  }
                })
                let obj = res.info[i];
                let pkey = null; //判断主键
                for (let i = 0; i < this.self.info.table[tbindex].fields.length; i++) { //判断是否 配置了唯一键
                  let tfield = this.self.info.table[tbindex].fields[i];
                  if (tfield.uniqRule) {
                    if (tfield.uniqRule.indexOf('pkey:') > -1) {
                      pkey = tfield.uniqRule.substring(5);
                      break;
                    }

                  }
                }
                // console.log(pkey)

                // console.log(this.self)
                if (pkey) {
                  for (let nn = 0; nn < this.self.info.table[tbindex].record.length; nn++) { //去除空记录
                    let sob = this.self.info.table[tbindex].record[nn];
                    if (JSON.stringify(sob) == "{}") {
                      this.self.info.table[tbindex].record.splice(nn, 1);
                    } else {
                      let rcordNull = true;
                      for (let keyf in sob) {
                        if (sob[keyf] != null) {
                          rcordNull = false
                        }
                      }
                      if (rcordNull) {
                        this.self.info.table[tbindex].record.splice(nn, 1);
                      }
                    }
                  }

                  let has = false; //判断记录是否重复
                  let rindex = 0;


                  for (let k = 0; k < this.self.info.table[tbindex].record.length; k++) {
                    let record = this.self.info.table[tbindex].record[k];
                    console.log(record[pkey], obj, obj[pkey])

                    if (record[pkey] == obj[pkey] || record[pkey.toLowerCase()] == obj[pkey.toUpperCase()] || record[pkey.toUpperCase()] == obj[pkey.toLowerCase()]) {
                      has = true;
                      rindex = k;
                    }
                  }
                  console.log(rindex, has)
                  if (has) {
                    console.log(rindex, this.self.info.table[tbindex].record.length)
                    this.setTableRecord(tbindex, rindex, obj);
                  } else {
                    console.log(rindex, this.self.info.table[tbindex].record.length)
                    this.setTableRecord(tbindex, rindex, obj);
                    this.self.setTableSetNouserEvent();
                  }
                } else {
                  // 单选更新当前行，多选新增
                  let tr = this.self.tableset.trs[this.self.activetr]
                  if (!tr.tds[this.self.activetd].com.comattrs.multiSelect) {
                    //单选
                    console.log(888888, tr.rindex)
                    this.self.info.table[tbindex].record = [];
                    if (joinObj && joinObj.hasOwnProperty("SUBJECT_TYPE") && joinObj["SUBJECT_TYPE"].indexOf(',') != -1) {
                      //包含多条数据
                      let testObjArr = [], len = null, testObjArr1 = [];
                      for (const key in joinObj) {
                        let testObj = "";
                        len = joinObj[key].split(',').length;
                        testObj = key + ":" + joinObj[key];
                        testObjArr.push(testObj);
                      }
                      for (let i = 0; i < len; i++) {
                        testObjArr1.push({})
                      }
                      testObjArr.forEach(element => {
                        for (let i = 0; i < len - 1; i++) {
                          testObjArr1[i][element.split(':')[0]] = element.split(':')[1].split(",")[i];
                        }
                      });
                      this.self.info.table[tbindex].record = testObjArr1;
                    }
                    for (let nn = 0; nn < this.self.info.table[tbindex].record.length; nn++) { //去除空记录
                      let sob = this.self.info.table[tbindex].record[nn];
                      if (JSON.stringify(sob) == "{}") {
                        this.self.info.table[tbindex].record.splice(nn, 1);
                      } else {
                        let rcordNull = true;
                        for (let keyf in sob) {
                          if (sob[keyf] != null) {
                            rcordNull = false
                          }
                        }
                        if (rcordNull) {
                          this.self.info.table[tbindex].record.splice(nn, 1);
                        }
                      }
                    }

                    this.setTableRecord(tbindex, this.self.info.table[tbindex].record.length, obj);
                    this.self.setTableSetNouserEvent();
                  } else {
                    console.log('BBBBBBBBBBB', tr.tds[this.self.activetd].com.comattrs.multiSelect)
                    for (let nn = 0; nn < this.self.info.table[tbindex].record.length; nn++) { //去除空记录
                      let sob = this.self.info.table[tbindex].record[nn];
                      if (JSON.stringify(sob) == "{}") {
                        this.self.info.table[tbindex].record.splice(nn, 1);
                      } else {
                        let rcordNull = true;
                        for (let keyf in sob) {
                          if (sob[keyf] != null) {
                            rcordNull = false
                          }
                        }
                        if (rcordNull) {
                          this.self.info.table[tbindex].record.splice(nn, 1);
                        }
                      }
                    }

                    this.setTableRecord(tbindex, this.self.info.table[tbindex].record.length, obj);
                    this.self.setTableSetNouserEvent();
                  }

                }
              }
            }
          }
        })
      }
    }

    //	this.self.calc(this.trindex,this.tdindex);
    //	  this.self.$forceUpdate() //强制刷新
    //	  this.self.settOption&&this.self.settOption() //刷新下拉信息
  }
}

export {
  userevent
}